package com.vote.wx.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.vote.common.core.domain.ResponseResult;
import com.vote.common.core.domain.entity.SysUser;
import com.vote.common.core.domain.model.LoginUser;
import com.vote.common.core.redis.RedisCache;
import com.vote.dto.WeChatDTO;
import com.vote.framework.web.service.TokenService;
import com.vote.system.service.ISysUserService;
import com.vote.utils.JSONUtils;
import com.vote.vote.util.RandomUtils;
import com.vote.wx.service.PublicCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author WanShen
 * @date 2024年01月26日 15:30
 */
@Service
@Slf4j
public class PublicCodeServiceImpl implements PublicCodeService {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private ISysUserService userMapper;

    //redis的
    @Autowired
    private RedisCache redisService;

    @Autowired
    private TokenService tokenService;

    @Override
    public ResponseResult login(String code) {
        WeChatDTO oauth2AccessToken = getOauth2AccessToken(code);
        if (oauth2AccessToken != null) {
            //        初始化一下
            SysUser user = weChatInit(oauth2AccessToken.getOpenid());
            //        生成token
            LoginUser loginUser = new LoginUser().setUser(user);

            String token = tokenService.createToken(loginUser);
//        存入token
            user.setToken(token);
            return ResponseResult.success(user);
        } else return ResponseResult.error("请点击头像重新登陆!");

    }

    //通过code换取网页授权access_token：https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html#1
//接口：https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
    public WeChatDTO getOauth2AccessToken(String code) {

        String appId = "wxb079ec102fdec136";
        String secret = "d500f05eec9fed0cb8f23819595e3bf0";
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";

        //1、构建body参数
        JSONObject jsonObject = new JSONObject();

        //2、添加请求头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        //3、组装请求头和参数
        HttpEntity<String> formEntity = new HttpEntity<>(JSON.toJSONString(jsonObject), headers);

        //4.发送请求
        ResponseEntity<String> stringResponseEntity = null;

        try {
            stringResponseEntity = restTemplate.getForEntity(url, String.class, formEntity);
            log.info("url->{}", url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //5、获取http状态码
        int statusCodeValue = stringResponseEntity.getStatusCodeValue();
        log.info("httpCode-----" + statusCodeValue);

        //6、获取返回体
        String body = stringResponseEntity.getBody();
        WeChatDTO weChatDTO = JSONUtils.JsonForObj(body, WeChatDTO.class);
        if (weChatDTO.getErrcode() != null) return null;
        System.err.println("body==" + body);

        return weChatDTO;
    }

    public SysUser weChatInit(String openId) {
        SysUser userInfoVO = userMapper.selectUserByUserName(openId);
        if (userInfoVO != null) {
            return userInfoVO;
        } else {
//                用户不存在 新用户
            userInfoVO = new SysUser().setNickName("WECHAT-bn" + RandomUtils.generationNumberChar(4))
                    .setUserName(openId);
//                调用注册的方法
            userMapper.registerUser(userInfoVO);

            return userInfoVO;
        }
    }

}
